﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using DevExpress.Xpf.Core;
using ChatApp.Client.Common;
using ChatApp.Client.ChatAppServiceReference;
using System.ServiceModel;


namespace ChatApp.Client
{
    /// <summary>
    /// Interaction logic for Login.xaml
    /// </summary>
    public partial class Login : DXWindow, IChatAppServiceCallback
    {
        public Login()
        {
            InitializeComponent();
            
            ChatAppGlobal.FormLogin = this;
            txtTenDangNhap.Focus();
        }

        private void btnDangNhap_Click(object sender, RoutedEventArgs e)
        {
            // Gọi hàm login từ service
            ChatAppServiceClient client = new ChatAppServiceClient(new InstanceContext(this));
            ChatAppGlobal.UserLogin = client.LoginUser(txtTenDangNhap.Text, ChatAppGlobal.EncodeMD5(txtMatKhau.Text));
            // Kiểm tra kết quả trả về
            if (ChatAppGlobal.UserLogin != null) // Nếu thành công
            {
                // Ẩn form login
                this.Hide();
                
                txtMatKhau.Text = null;
                // HIển thị form chính
                MainWindow main = new MainWindow();
                main.Show();
            }
            else
            {
                MessageBox.Show("Đăng nhập không thành công");
            }
        }

        private void btnDangKy_Click(object sender, RoutedEventArgs e)
        {
            ChatAppGlobal.FormLogin.Hide();
            DangKyNguoiDung formDayKy = new DangKyNguoiDung();
            formDayKy.txtTaiKhoan.Focus();
            formDayKy.Show();
        }

        

        private void DXWindow_Closed(object sender, EventArgs e)
        {
            Application.Current.Shutdown();
        }

        private void bExit_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            ChatAppGlobal.FormLogin.Close();
            Application.Current.Shutdown();
        }

        private void txtMatKhau_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.Key == Key.Enter)
            {
                btnDangNhap.RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); 
            }
        }

        private void txtTenDangNhap_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.Key == Key.Enter)
            {
                btnDangNhap.RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); 
            }
        }

        public void RefreshContentChat(int idRoom, string tenRoom, string userNameSend, string textChat, bool laChatRoom)
        {
        }
    }
}
